<template>
  <t-drawer
    :visible="visible"
    :header="isEdit ? '编辑任务' : '新增任务'"
    size="600px"
    placement="right"
    @close="handleClose"
  >
    <div class="add-mission-form">
      <t-form
        ref="formRef"
        :data="formData"
        :rules="formRules"
        label-align="right"
        label-width="100px"
        class="mission-form"
      >
        <t-form-item label="任务名称" name="name">
          <t-input v-model="formData.name" placeholder="请输入任务名称" clearable />
        </t-form-item>

        <t-form-item label="任务描述" name="description">
          <t-textarea
            v-model="formData.description"
            placeholder="请输入任务描述"
            :maxlength="200"
            show-limit
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </t-form-item>

        <t-form-item label="任务类型" name="missionType">
          <t-select v-model="formData.missionType" placeholder="请选择任务类型">
            <t-option
              v-for="(label, value) in MissionTypeLabels"
              :key="value"
              :value="value"
              :label="label"
            >
              {{ label }}
            </t-option>
          </t-select>
        </t-form-item>

        <t-form-item
          v-show="formData.missionType && !isQuestionnaireOrExamType"
          label="关联数据"
          name="missionRelatedData"
        >
          <t-select
            v-model="formData.missionRelatedData"
            placeholder="请先选择任务类型"
            :loading="relatedDataLoading"
            :disabled="!formData.missionType"
            clearable
          >
            <t-option
              v-for="item in relatedDataOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            >
              {{ item.label }}
            </t-option>
          </t-select>
        </t-form-item>

        <t-form-item label="无限期活动" name="isPerpetual">
          <t-switch
            v-model="formData.isPerpetual"
            :custom-value="[CommonStatus.YES, CommonStatus.NO]"
          />
        </t-form-item>

        <t-form-item
          v-show="formData.isPerpetual === CommonStatus.NO"
          label="时间范围"
          name="timeRange"
        >
          <t-date-range-picker
            v-model="formData.timeRange"
            :placeholder="['开始时间', '结束时间']"
            enable-time-picker
            clearable
            allow-input
          />
        </t-form-item>

        <t-form-item label="关联规则" name="pointsRuleId">
          <div class="rule-section">
            <t-radio-group v-model="formData.pointsRuleId">
              <t-radio
                v-for="rule in relatedRuleOptions"
                :key="rule.value"
                :value="rule.value"
                style="margin-bottom: 8px; display: block"
              >
                <div class="rule-option">
                  <div class="rule-title-wrapper">
                    <div class="rule-title">{{ rule.title }}</div>
                    <t-button
                      theme="primary"
                      variant="text"
                      size="small"
                      @click.stop="handleEditRule(rule)"
                      class="edit-rule-btn"
                    >
                      修改
                    </t-button>
                  </div>
                  <div class="rule-description">{{ rule.description }}</div>
                </div>
              </t-radio>
            </t-radio-group>

            <div class="rule-actions">
              <t-button theme="primary" variant="outline" size="small" @click="handleAddRule">
                <template #icon>
                  <t-icon name="add" />
                </template>
                新增规则
              </t-button>
            </div>
          </div>
        </t-form-item>
      </t-form>

      <!-- 新增/编辑规则弹框 -->
      <AddRuleDialog
        :visible="addRuleDialogVisible"
        :editData="editRuleData"
        :isEdit="isEditRule"
        @update:visible="addRuleDialogVisible = $event"
        @success="handleAddRuleSuccess"
      />
    </div>

    <!-- 底部按钮区域 -->
    <template #footer>
      <div class="drawer-footer">
        <t-button variant="outline" theme="default" @click="handleClose"> 取消 </t-button>
        <t-button theme="primary" @click="handleSubmit" :loading="submitLoading"> 确定 </t-button>
      </div>
    </template>
  </t-drawer>
</template>

<script>
import { MessagePlugin } from 'tdesign-vue';
import AddRuleDialog from './add-rule-dialog.vue';
import { getRulesList, getSurveyList } from '@/api/rules';
import { getDiseaseList } from '@/api/disease';
import { createMission, updateMission } from '@/api/mission';

// 任务类型枚举
const MissionType = {
  CATALOG: 'CATALOG', // 目录
  RECOMMEND: 'RECOMMEND', // 推荐
  EXAM: 'EXAM', // 考试
  QNAIRE: 'QNAIRE', // 问卷
};

// 通用状态枚举
const CommonStatus = {
  NO: 0,
  YES: 1,
};

// 任务类型标签
const MissionTypeLabels = {
  [MissionType.CATALOG]: '目录知识',
  [MissionType.RECOMMEND]: '推荐知识',
  [MissionType.EXAM]: '答题考试',
  [MissionType.QNAIRE]: '问卷调查',
};

export default {
  name: 'AddMissionDrawer',
  components: {
    AddRuleDialog,
  },
  model: {
    prop: 'visible',
    event: 'update:visible',
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    editData: {
      type: Object,
      default: () => null,
    },
  },
  data() {
    return {
      submitLoading: false,
      relatedDataLoading: false,
      MissionTypeLabels,
      CommonStatus,
      addRuleDialogVisible: false,
      isEditRule: false,
      editRuleData: null,

      // 表单数据
      formData: {
        name: '',
        description: '',
        missionType: '',
        timeRange: [],
        missionRelatedData: '',
        isPerpetual: CommonStatus.NO,
        pointsRuleId: null,
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 2, max: 50, message: '任务名称长度应在2-50个字符之间', trigger: 'blur' },
        ],
        description: [{ max: 200, message: '任务描述长度不能超过200个字符', trigger: 'blur' }],
        missionType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
        timeRange: [
          {
            trigger: 'change',
            validator: (val) => {
              // 如果是无限期活动，不校验时间范围
              if (this.formData.isPerpetual === CommonStatus.YES) {
                return { result: true, message: '', type: 'success' };
              }
              // 非无限期活动时，必须选择时间范围
              if (!Array.isArray(val) || val.length !== 2 || !val[0] || !val[1]) {
                return { result: false, message: '请选择任务时间范围', type: 'error' };
              }
              return { result: true, message: '', type: 'success' };
            },
          },
        ],
        missionRelatedData: [
          {
            required: false,
            message: '请选择关联数据',
            trigger: 'change',
            validator: (val) => {
              // 问卷和答题类型不需要关联数据
              if (this.isQuestionnaireOrExamType) {
                return { result: true, message: '', type: 'success' };
              }
              // 其他类型需要关联数据
              if (!val) {
                return { result: false, message: '请选择关联数据', type: 'error' };
              }
              return { result: true, message: '', type: 'success' };
            },
          },
        ],
        pointsRuleId: [
          { required: true, message: '请选择关联规则', trigger: 'change', type: 'number' },
        ],
      },

      // 关联数据选项 - 动态加载
      relatedDataOptions: [],

      // 关联规则选项 - 改为从接口获取
      relatedRuleOptions: [],
    };
  },

  computed: {
    // 判断是否为问卷或答题类型
    isQuestionnaireOrExamType() {
      return this.formData.missionType === MissionType.QNAIRE ||
             this.formData.missionType === MissionType.EXAM;
    },
  },

  watch: {
    visible: {
      async handler(newVal) {
        if (newVal) {
          this.resetForm();
          this.loadRulesList();
          // 如果是编辑模式且有编辑数据，则填充表单
          if (this.isEdit && this.editData) {
            await this.fillEditData();
          }
        }
      },
      immediate: true,
    },
    // 监听任务类型变化，动态加载关联数据
    'formData.missionType': {
      handler(newType, oldType) {
        if (newType && newType !== oldType) {
          // 如果是问卷或答题类型，清空关联数据并不加载
          if (newType === MissionType.QNAIRE || newType === MissionType.EXAM) {
            this.formData.missionRelatedData = '';
            this.relatedDataOptions = [];
            return;
          }

          // 编辑模式下，如果是首次设置任务类型且没有旧值，不重复加载
          // 因为在 fillEditData 中已经预先加载了数据
          if (this.isEdit && !oldType && this.relatedDataOptions.length > 0) {
            return;
          }

          // 只有在非编辑模式或者类型真正发生变化时才清空关联数据
          if (!this.isEdit || (this.isEdit && oldType)) {
            this.formData.missionRelatedData = '';
          }
          this.loadRelatedDataByType(newType);
        } else if (!newType) {
          this.relatedDataOptions = [];
        }
      },
      immediate: false,
    },
  },

  methods: {
    // 根据任务类型加载对应的关联数据
    async loadRelatedDataByType(type) {
      // 问卷和答题类型不需要关联数据
      if (type === MissionType.QNAIRE || type === MissionType.EXAM) {
        this.relatedDataOptions = [];
        return;
      }

      this.relatedDataLoading = true;
      try {
        switch (type) {
          case MissionType.CATALOG:
            await this.loadDiseaseData();
            break;
          case MissionType.RECOMMEND:
            await this.loadRecommendData();
            break;
          default:
            this.relatedDataOptions = [];
        }
      } catch (error) {
        console.error('加载关联数据失败:', error);
        MessagePlugin.error('加载关联数据失败');
        this.relatedDataOptions = [];
      } finally {
        this.relatedDataLoading = false;
      }
    },

    // 加载疾病数据 - 目录知识类型和推荐知识类型
    async loadDiseaseData() {
      const response = await getDiseaseList();
      if (response.data && response.data.data) {
        // 根据当前任务类型设置不同的标签前缀
        const labelPrefix = this.formData.missionType === MissionType.CATALOG ? '目录知识' : '推荐知识';

        this.relatedDataOptions = response.data.data.map((disease) => ({
          value: Number(disease.id), // 确保 value 是数字类型
          label: `${labelPrefix} - ${disease.name || disease.categoryName}`,
          originalData: disease,
        }));

        console.log(`已加载${labelPrefix}的疾病数据:`, this.relatedDataOptions);
      }
    },

    // 加载推荐内容数据 - 推荐知识类型
    async loadRecommendData() {
      // 推荐知识类型也使用疾病数据
      const response = await getDiseaseList();
      if (response.data && response.data.data) {
        this.relatedDataOptions = response.data.data.map((disease) => ({
          value: disease.id,
          label: `推荐知识 - ${disease.name || disease.categoryName}`,
          originalData: disease,
        }));
      }
    },

    // 加载考试数据 - 答题考试类型 [已废弃：答题类型不再需要关联数据]
    async loadExamData() {
      try {
        const response = await getSurveyList();
        console.log('考试数据响应:', response);

        this.relatedDataOptions = (response?.data?.data?.data ?? [])
          .filter((item) => item.surveyType === 'exam')
          .map((item) => {
            return {
              value: item?.surveyPath ?? '',
              label: item?.title ?? '',
              originalData: item,
            };
          });
      } catch (error) {
        console.error('获取考试数据失败:', error);
        MessagePlugin.warning('获取考试数据失败，使用默认选项');
        // 接口调用失败时使用默认选项
        this.relatedDataOptions = [];
      }
    },

    // 加载问卷数据 - 问卷调查类型 [已废弃：问卷类型不再需要关联数据]
    async loadSurveyData() {
      try {
        const response = await getSurveyList();

        this.relatedDataOptions = (response?.data?.data?.data ?? [])
          .filter((item) => item.surveyType !== 'exam')
          .map((item) => {
            return {
              value: item?.surveyPath ?? '',
              label: item?.title ?? '',
              originalData: item,
            };
          });
      } catch (error) {
        console.error('获取问卷数据失败:', error);
        MessagePlugin.warning('获取问卷数据失败，使用默认选项');
        // 接口调用失败时使用默认选项
        this.relatedDataOptions = [];
      }
    },

    // 加载关联数据选项 - 保留原方法以备用
    async loadRelatedData() {
      // 这个方法现在被 loadRelatedDataByType 替代
      // 保留以防需要统一加载所有数据的场景
    },

    // 加载规则列表
    async loadRulesList() {
      try {
        // 先尝试不带参数的请求
        let response = await getRulesList();

        // 打印调试信息，查看实际返回的数据结构
        console.log('规则列表响应数据:', response);

        // 如果第一次请求没有描述字段，尝试带参数的请求
        if (response.data) {
          const sampleRule = Array.isArray(response.data.data)
            ? response.data.data[0]
            : Array.isArray(response.data)
            ? response.data[0]
            : null;

          console.log('示例规则数据:', sampleRule);

          // 如果没有描述字段，尝试带参数请求
          if (sampleRule && !sampleRule.description && !sampleRule.ruleDescription) {
            console.log('尝试获取包含描述的完整数据...');
            try {
              response = await getRulesList({ includeDescription: true });
              console.log('带参数的响应数据:', response);
            } catch (paramError) {
              console.log('带参数请求失败，使用原始数据');
            }
          }
        }

        // 根据接口返回的数据格式进行处理
        if (response.data && response.data.data) {
          this.relatedRuleOptions = response.data.data.map((rule) => {
            console.log('处理规则:', rule);
            return {
              value: rule.id,
              title: rule.ruleName,
              description: `完成次数：${rule.targetCount || '不限'}，每次获得积分：${
                rule.fixedPoints || 0
              }`,
              originalData: {
                ...rule,
                // 尝试多种可能的描述字段名
                description:
                  rule.description || rule.ruleDescription || rule.desc || rule.content || '',
              },
            };
          });
        } else if (response.data) {
          this.relatedRuleOptions = response.data.map((rule) => {
            console.log('处理规则:', rule);
            return {
              value: rule.id,
              title: rule.ruleName,
              description: `完成次数：${rule.targetCount || '不限'}，每次获得积分：${
                rule.fixedPoints || 0
              }`,
              originalData: {
                ...rule,
                // 尝试多种可能的描述字段名
                description:
                  rule.description || rule.ruleDescription || rule.desc || rule.content || '',
              },
            };
          });
        }

        console.log('最终规则选项:', this.relatedRuleOptions);
      } catch (error) {
        console.error('获取规则列表失败:', error);
        MessagePlugin.error('获取规则列表失败');

        // 如果接口调用失败，使用默认的规则选项作为备选
        this.relatedRuleOptions = [];
      }
    },

    // 关闭抽屉
    handleClose() {
      this.$emit('update:visible', false);
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.formData = {
        name: '',
        description: '',
        missionType: '',
        timeRange: [],
        missionRelatedData: '',
        isPerpetual: CommonStatus.NO,
        pointsRuleId: null,
      };

      // 清空关联数据选项
      this.relatedDataOptions = [];

      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate();
      });
    },

    // 填充编辑数据
    async fillEditData() {
      if (this.editData) {
        // 先保存原始的关联数据值
        let originalRelatedData = this.editData.missionRelatedData || '';

        // 对于目录和推荐类型的任务，将 missionRelatedData 转为数字类型
        if (this.editData.missionType === MissionType.CATALOG || this.editData.missionType === MissionType.RECOMMEND) {
          // 如果是字符串类型的数字，转为数字
          if (originalRelatedData && typeof originalRelatedData === 'string') {
            const numValue = parseInt(originalRelatedData, 10);
            if (!isNaN(numValue)) {
              originalRelatedData = numValue;
            }
          }
        }

        // 对于问卷和答题类型，不需要关联数据
        if (this.editData.missionType === MissionType.QNAIRE || this.editData.missionType === MissionType.EXAM) {
          originalRelatedData = '';
        }

        // 先加载关联数据，避免后续 watch 触发重复加载
        if (this.editData.missionType &&
            this.editData.missionType !== MissionType.QNAIRE &&
            this.editData.missionType !== MissionType.EXAM) {
          await this.loadRelatedDataByType(this.editData.missionType);
        }

        this.formData = {
          name: this.editData.name || '',
          description: this.editData.description || '',
          missionType: this.editData.missionType || '',
          missionRelatedData: originalRelatedData,
          isPerpetual: this.editData.isPerpetual ?? CommonStatus.NO,
          pointsRuleId: this.editData.pointsRule?.id || null,
          timeRange: [],
        };

        // 如果有开始和结束时间，填充时间范围
        if (this.editData.startDate && this.editData.endDate) {
          this.formData.timeRange = [this.editData.startDate, this.editData.endDate];
        }
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        // 验证表单
        const valid = await this.$refs.formRef.validate();
        if (valid !== true) {
          return;
        }

        this.submitLoading = true;

        // 准备提交数据
        let missionRelatedData = this.formData.missionRelatedData || null;

        // 问卷和答题类型不需要关联数据
        if (this.formData.missionType === MissionType.QNAIRE || this.formData.missionType === MissionType.EXAM) {
          missionRelatedData = null;
        } else {
          // 对于目录和推荐类型的任务，将 missionRelatedData 序列化为字符串
          if (this.formData.missionType === MissionType.CATALOG || this.formData.missionType === MissionType.RECOMMEND) {
            if (missionRelatedData !== null && typeof missionRelatedData === 'number') {
              missionRelatedData = String(missionRelatedData);
            }
          }
        }

        const submitData = {
          name: this.formData.name,
          description: this.formData.description,
          missionType: this.formData.missionType,
          missionRelatedData: missionRelatedData,
          isPerpetual: this.formData.isPerpetual,
          pointsRuleId: Number(this.formData.pointsRuleId),
        };

        // 如果不是无限期活动，添加开始和结束时间
        if (this.formData.isPerpetual === CommonStatus.NO) {
          submitData.startDate = this.formData.timeRange[0];
          submitData.endDate = this.formData.timeRange[1];
        }

        if (this.isEdit && this.editData?.id) {
          // 编辑模式 - 调用更新接口
          await updateMission(this.editData.id, submitData);
          MessagePlugin.success('任务更新成功');
        } else {
          // 新增模式 - 调用创建接口
          await createMission(submitData);
          MessagePlugin.success('任务创建成功');
        }

        this.$emit('success', submitData);
        this.handleClose();
      } catch (error) {
        const message = error?.response?.data?.message ?? (this.isEdit ? '更新任务失败' : '创建任务失败');
        MessagePlugin.error(message);
      } finally {
        this.submitLoading = false;
      }
    },

    // 新增规则
    handleAddRule() {
      this.isEditRule = false;
      this.editRuleData = null;
      this.addRuleDialogVisible = true;
    },

    // 编辑规则
    handleEditRule(rule) {
      console.log('准备编辑规则:', rule);
      console.log('规则原始数据:', rule.originalData);

      // 尝试多种可能的描述字段名
      const description =
        rule.originalData?.description ||
        rule.originalData?.ruleDescription ||
        rule.originalData?.desc ||
        rule.originalData?.content ||
        '';

      console.log('提取的描述:', description);

      this.isEditRule = true;
      this.editRuleData = {
        id: rule.value,
        title: rule.title,
        description: description,
        completionCount: rule.originalData?.targetCount || 1,
        rewardPoints: rule.originalData?.fixedPoints || 10,
      };

      console.log('编辑数据:', this.editRuleData);
      this.addRuleDialogVisible = true;
    },

    // 新增规则成功回调
    handleAddRuleSuccess(newRule) {
      // 重新加载规则列表，确保获取最新数据
      this.loadRulesList();

      // 自动选择新添加的规则
      this.formData.pointsRuleId = newRule.value || newRule.id;
    },
  },
};
</script>

<style lang="less" scoped>
.add-mission-form {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.mission-form {
  width: 100%;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.rule-option {
  display: flex;
  flex-direction: column;
  padding: 8px 0;
}

.rule-title-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.rule-title {
  font-weight: 500;
  color: #333;
  font-size: 14px;
  flex: 1;
}

.edit-rule-btn {
  margin-left: 8px;
  padding: 0 4px;
  height: 20px;
  font-size: 12px;
}

.rule-description {
  margin-top: 4px;
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

.rule-section {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.rule-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-start;
}

.form-tip {
  margin-top: 8px;
  color: #999;
  font-size: 12px;
}
</style>
